package Viewer;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;

/**
 * A Optimized file chooser with self defined short links. Gives possibility to
 * add new link buttons.<br>
 * Reads the links out of the filechooser_links.gs file
 * 
 * @author Stefan Lorenz<br>
 * <br>
 *         28.11.2012
 */
@SuppressWarnings("serial")
public class FileChooserX extends JFileChooser {

	/**
	 * Constructor of the optimized filechooser
	 */
	public FileChooserX() {
		this.setFileHidingEnabled(false);
		this.setPreferredSize(new Dimension(600, 600));
		try {
			readAdditionalLinks();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Reads the filechooser_links.gs file and adds additional directory buttons
	 * to filechooser
	 * 
	 * @throws IOException
	 */
	private void readAdditionalLinks() throws IOException {
		try {
			BufferedReader r = new BufferedReader(new FileReader(new File(
					"filechooser_links.gs")));
			String al = "";
			while ((al = r.readLine()) != null) {
				JButton butt = new JButton(al.split(";")[0]);
				((JPanel) ((JPanel) this.getComponent(0)).getComponent(0))
						.add(butt);
				addActionlistener(butt, new File(al.split(";")[1]));
			}
			r.close();
		} catch (Exception e) {
			e.fillInStackTrace();
		}
	}

	/**
	 * Adds Actionlisteners to the new added buttons
	 * 
	 * @param b
	 *            Button to add
	 * @param file
	 *            path of link
	 */
	private void addActionlistener(JButton b, final File file) {
		ActionListener ac = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				setCurrentDirectory(file);
			}
		};
		b.addActionListener(ac);
	}
}
